import storage from '@/utils/storage'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, logout, getInfo } from '@/api/login'
import type { LoginReq, UserInfo } from '@/api/login/type'
import type { BaseResponse } from '@/api/base'
import type { UserState } from './type'
import { toast } from '@/utils/common'

const userInfoKey = 'user_info'

const user = {
  state: (): UserState => {
    return {
      token: getToken(),
      userInfo: storage.get(userInfoKey),
    }
  },

  mutations: {
    SET_TOKEN: (state: { token: string }, token: string) => {
      state.token = token
      setToken(token)
    },
    SET_USER_INFO: (state: { userInfo: UserInfo }, userInfo: UserInfo) => {
      state.userInfo = userInfo
      storage.set(userInfoKey, userInfo)
    }
  },

  actions: {
    // 登录
    async Login({ commit }, loginReq: LoginReq) {
      try {
        const res: BaseResponse = await login(loginReq);
        commit('SET_TOKEN', res.data)
      } catch (e: BaseResponse) {
        throw e
      }
    },
    // 获取用户信息
    async GetInfo({ commit }) {
      try {
        const res: BaseResponse = await getInfo()
        commit('SET_USER_INFO', res.data)
      } catch (e: BaseResponse) {
        throw e
      }
    },
    // 退出系统
    async Logout({ commit }) {
      await logout()
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', {})
      removeToken()
      storage.remove(userInfoKey)
    },
    // 退出系统 用于401 token 过期,不走后台
    LogoutLocal({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', {})
      removeToken()
      storage.remove(userInfoKey)
    },
  }
}

export default user